﻿using System;
using System.Windows.Forms;
using Usido.CRM.Core.Extensions;
using Usido.CRM.IRepository;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 药品预留数界面 : Form
    {
        public 药品预留数界面()
        {
            InitializeComponent();
        }

        #region 窗体绘制

        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        #endregion 窗体绘制

        private readonly IStockProductBalanceRepository stockProductBalance = new StockProductBalanceRepository();

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            BindData();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BindData();
        }

        public void BindData()
        {
            string seacher = textBox1.Text.Trim();
            string where = $"  WHERE ProductCode like '%{seacher}%'  or ProductName like '%{seacher}%'";
            var stockBalanceList = stockProductBalance.GetStockBalanceList(where);
            Dgv_Ypyy.AutoGenerateColumns = false;
            Dgv_Ypyy.DataSource = stockBalanceList;
        }

        /// <summary>
        /// 设置药品预留数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (Dgv_Ypyy.SelectedRows[0].Cells["Id"] == null)
            {
                MessageBox.Show("请选择有效行");
                return;
            }
            if (textBox2.Text.Trim() == "")
            {
                MessageBox.Show("请填写预留数量！");
                return;
            }
            decimal quantity = 0.0M;
            if (!decimal.TryParse(textBox2.Text.Trim(), out quantity))
            {
                MessageBox.Show("请填写正确格式的预留数量！");
                return;
            }
            string id = Dgv_Ypyy.SelectedRows[0].Cells["Id"].Value.ToString();//选中行ID

            if (stockProductBalance.UpdateReservedStock(id.ToInt(), quantity))
            {
                MessageBox.Show("设置成功");
                textBox2.Text = "";
                BindData();
            }
            else
            {
                MessageBox.Show("设置失败，请稍后重试");
            }
        }

        private void 药品预留数界面_Load(object sender, EventArgs e)
        {
            BindData();
        }
    }
}